package com.mall.auth.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.mall.api.user.UserFeignClient;
import com.mall.api.user.dto.UserDTO;
import com.mall.auth.vo.LoginVO;
import com.mall.auth.vo.RegisterVO;
import com.mall.common.exception.BusinessException;
import com.mall.common.result.Result;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final UserFeignClient userFeignClient;

    @PostMapping("/login")
    public Result<String> login(@RequestBody @Valid LoginVO loginVO) {
        // 查询用户
        Result<UserDTO> userResult = userFeignClient.getUserByUsername(loginVO.getUsername());
        if (userResult.getCode() != 200 || userResult.getData() == null) {
            throw new BusinessException("用户不存在");
        }
        
        UserDTO userDTO = userResult.getData();
        
        // 验证密码
        String encryptedPassword = DigestUtils.md5DigestAsHex(loginVO.getPassword().getBytes());
        if (!encryptedPassword.equals(userDTO.getPassword())) {
            throw new BusinessException("密码错误");
        }
        
        // 登录
        StpUtil.login(userDTO.getId());
        
        return Result.success("登录成功", StpUtil.getTokenValue());
    }
    
    @PostMapping("/register")
    public Result<String> register(@RequestBody @Valid RegisterVO registerVO) {
        // 注册用户
        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(registerVO.getUsername());
        userDTO.setPassword(registerVO.getPassword());
        userDTO.setNickname(registerVO.getNickname());
        userDTO.setEmail(registerVO.getEmail());
        userDTO.setPhone(registerVO.getPhone());
        
        userFeignClient.register(userDTO);
        
        return Result.success("注册成功");
    }
    
    @PostMapping("/logout")
    public Result<String> logout() {
        StpUtil.logout();
        return Result.success("退出成功");
    }
} 